package com.clementheliou.cheliou.web.core.listener;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.web.context.support.WebApplicationContextUtils;

import com.clementheliou.cheliou.web.controller.user.UserBean;

/**
 * Listener about session creations and destructions. It notifies the
 * {@link UserBean} of these ones to enable and improve the locales and members
 * caches.
 * 
 * @author Clément HELIOU (clement.heliou@gmail.com)
 * @see {@link HttpSessionListener};
 * @see {@link UserBean}.
 * @since 1.0
 */
public class DelegationHttpSessionListener implements HttpSessionListener {

	/**
	 * The bean that will be notified of session destructions.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @see {@link UserBean}.
	 * @since 1.0
	 */
	private UserBean userBean;

	/**
	 * <i> {@inheritDoc}</i>
	 * <p>
	 * Nothing to do at this time.
	 * </p>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@Override
	public void sessionCreated(HttpSessionEvent se) {
	}

	/**
	 * <i> {@inheritDoc}</i>
	 * <p>
	 * Notifies the {@link UserBean} that a session has been destroyed.
	 * </p>
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @since 1.0
	 */
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		getUserBean(se).clearSessionCaches(se);
	}

	/**
	 * Getter for the {@link #userBean}. This last one is retrieved from the
	 * current application context thanks to {@link WebApplicationContextUtils}.
	 * 
	 * @author Clément HELIOU (clement.heliou@gmail.com)
	 * @param se the {@link HttpSessionEvent} that triggers this getter.
	 * @return the {@link UserBean}.
	 * @see {@link UserBean};
	 * @see {@link WebApplicationContextUtils}.
	 * @since 1.0
	 */
	private UserBean getUserBean(HttpSessionEvent se) {
		if (null == userBean) {
			userBean = WebApplicationContextUtils.getRequiredWebApplicationContext(se.getSession().getServletContext()).getBean(UserBean.class);
		}
		return userBean;
	}

}
